package com.example.qqviewspringboot.controller;

import com.example.qqviewspringboot.data.Friendship;
import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.dto.FriendshipDto;
import com.example.qqviewspringboot.repository.FriendshipRepository;
import com.example.qqviewspringboot.repository.UserRepository;
import com.example.qqviewspringboot.security.CustomUserDetails;
import com.example.qqviewspringboot.service.FriendshipService;
import com.example.qqviewspringboot.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/friendships")
public class FriendshipController {
    private static final Logger log = LoggerFactory.getLogger(FriendshipController.class);

    @Autowired
    private FriendshipService friendshipService;

    @Autowired
    private FriendshipRepository friendshipRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private NotificationService notificationService;

    @PostMapping("/add")
    public ResponseEntity<String> addFriend(@Valid @RequestBody Map<String, Long> params) {
        Long userId = params.get("userId");
        Long friendId = params.get("friendId");
        friendshipService.addFriend(userId, friendId);
        return ResponseEntity.ok("Friend request sent successfully");
    }


    @PostMapping("/request")
    public ResponseEntity<String> sendFriendRequest(@RequestBody Map<String, Object> requestBody) {
        // 从请求体中提取 userId 和 friendName
        Long userId = requestBody.containsKey("userId") ? Long.valueOf(requestBody.get("userId").toString()) : null;
        String friendName = requestBody.containsKey("friendName") ? requestBody.get("friendName").toString() : null;

        // 校验参数合法性
        if (userId == null) {
            return ResponseEntity.badRequest().body("User ID is required");
        }
        if (friendName == null || friendName.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("Friend name is required");
        }

        // 检查 friendName 是否对应系统中的用户
        Optional<User> friendOptional = userRepository.findByUsernameIgnoreCase(friendName);
        if (!friendOptional.isPresent()) {
            return ResponseEntity.badRequest().body("User with the provided username does not exist");
        }

        User friend = friendOptional.get();
        Long friendId = friend.getId();

        // 检查是否已经存在好友关系
        Optional<Friendship> existingFriendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId);
        if (existingFriendship.isPresent()) {
            return ResponseEntity.badRequest().body("Friendship already exists or is pending");
        }

        // 创建好友请求
        Friendship friendship = new Friendship();
        friendship.setUserId(userId);
        friendship.setFriendId(friendId);
        friendship.setStatus(Friendship.Status.PENDING);

        // 保存好友请求
        try {
            friendshipRepository.save(friendship);
        } catch (Exception e) {
            // 日志记录
            log.error("Failed to create friendship request for userId: {} and friendId: {}", userId, friendId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create friendship request");
        }

        // 发送通知
        try {
            notificationService.createNotification(friendId, "You have a new friend request from user " + userId, "FRIEND_REQUEST");

        } catch (Exception e) {
            // 日志记录
            log.error("Failed to send notification for friendId: {}", friendId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to send notification");
        }

        return ResponseEntity.ok("Friend request sent successfully");
    }


    @GetMapping("/pending")
    public ResponseEntity<List<User>> getPendingFriendRequests(@RequestParam Long userId) {
        // 使用 Repository 自定义方法直接查询
        List<User> senders = friendshipRepository.findPendingRequestSenders(userId, Friendship.Status.PENDING);
        return ResponseEntity.ok(senders);
    }


    // 加载好友申请列表
//    @GetMapping("/pending")
//    public ResponseEntity<List<User>> getPendingFriendRequests(@RequestParam Long userId) {
//        List<Friendship> pendingRequests = friendshipRepository.findByFriendIdAndStatus(userId, Friendship.Status.PENDING);
//        List<User> senders = new ArrayList<>();
//        for (Friendship request : pendingRequests) {
//            userRepository.findById(request.getUserId()).ifPresent(senders::add);
//        }
//        return ResponseEntity.ok(senders);
//    }

    @GetMapping("/check")
    public ResponseEntity<String> checkFriendshipStatus(@RequestParam Long userId, @RequestParam Long friendId) {
        String status = friendshipService.getFriendshipStatus(userId, friendId);
        return ResponseEntity.ok(status);
    }

    @PostMapping("/accept")
    public ResponseEntity<String> acceptFriendRequest(@RequestBody FriendshipDto friendshipDto) {
        Long userId = friendshipDto.getUserId(); // 当前用户ID
        Long friendId = friendshipDto.getFriendId(); // 申请的好友ID

        log.debug("Processing friend request acceptance: userId={}, friendId={}", userId, friendId);

        try {
            // 更新好友关系状态
            friendshipService.acceptFriendRequest(userId, friendId);
            log.info("Friend request accepted successfully: userId={}, friendId={}", userId, friendId);
            return ResponseEntity.ok("Friend request accepted successfully.");
        } catch (IllegalArgumentException e) {
            log.warn("Accept failed due to invalid request: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            log.error("Error accepting friend request: userId={}, friendId={}", userId, friendId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to accept friend request.");
        }
    }



    @PostMapping("/reject")
    public ResponseEntity<String> rejectFriendRequest(@RequestBody FriendshipDto friendshipDto) {
        Long userId = friendshipDto.getUserId(); // 当前用户ID
        Long friendId = friendshipDto.getFriendId(); // 申请的好友ID

        log.debug("Processing friend request rejection: userId={}, friendId={}", userId, friendId);

        try {
            // 更新好友关系状态
            friendshipService.rejectFriendRequest(userId, friendId);
            log.info("Friend request rejected successfully: userId={}, friendId={}", userId, friendId);
            return ResponseEntity.ok("Friend request rejected successfully.");
        } catch (IllegalArgumentException e) {
            log.warn("Reject failed due to invalid request: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            log.error("Error rejecting friend request: userId={}, friendId={}", userId, friendId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to reject friend request.");
        }
    }



    // 加载好友列表
    @GetMapping("/friends")
    public ResponseEntity<List<User>> getFriends(@RequestParam Long userId) {
        log.debug("Loading friends for userId={}", userId);

        try {
            // 获取所有接受的好友关系
            List<Friendship> friendships = friendshipRepository.findByUserIdOrFriendIdAndStatus(userId, Friendship.Status.ACCEPTED);
            List<User> friends = new ArrayList<>();

            for (Friendship friendship : friendships) {
                // 确定好友的ID
                Long friendId = (friendship.getUserId().equals(userId)) ? friendship.getFriendId() : friendship.getUserId();
                userRepository.findById(friendId).ifPresent(friends::add);
            }

            log.info("Successfully loaded friends for userId={}, total friends={}", userId, friends.size());
            return ResponseEntity.ok(friends);
        } catch (Exception e) {
            log.error("Error loading friends for userId={}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


}
